package com.robusta.cityuate.services;

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Set;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.entity.ByteArrayEntity;
import org.json.JSONException;
import org.json.JSONObject;

import com.robusta.cityuate.activities.SpotCreateEditActivity;
import com.robusta.cityuate.objects.Spot;
import com.robusta.cityuate.utils.ConnectionUtils;

import android.content.Context;
import android.content.Intent;
import android.util.Log;

public class SpotCreateEditService extends HTTPService {

	private static final String REQUEST_URL = "/spots";
	private static final String SPOT = "spot";
	private static final String TAG = SpotCreateEditService.class.getName();
	private static final String IMAGE = "image";
	private static boolean isEdit = false;
	private final Context mContext = this;

	@Override
	protected void onResponse() {
		Intent createSpotUIupdate = new Intent(assignedFilter);
		Log.d(TAG, "AssignedFilter= " + assignedFilter);
		switch (responseStatusCode) {
		case HttpStatus.SC_CREATED: // successful spot
		case HttpStatus.SC_NO_CONTENT: {// successful spot
			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, true, assignedFilter,
					null);
			// update UI if active
			createSpotUIupdate.putExtra(RESUlT, true);
			// Log.d(TAG, "Success Token " + token);
			break;
		}
		
		
		case HttpStatus.SC_NOT_FOUND:{
			JSONObject responseMsg;
			String msg = "";
			try {
				responseMsg = new JSONObject(responseString);
				msg= responseMsg.getString(MESSAGE);
				// remove connection from shared pref
				ConnectionUtils.setDisconnecting(mContext, false, assignedFilter,
						msg);
				// update UI if active
				createSpotUIupdate.putExtra(RESUlT, false);
				
			} catch (JSONException e) {
				e.printStackTrace();

			}
			break;
		}
		case HttpStatus.SC_UNPROCESSABLE_ENTITY: {
			// extract the message
			JSONObject responseMsg;
			String msg = "";
			try {
				responseMsg = new JSONObject(responseString);
				for (@SuppressWarnings("unchecked")
				Iterator<String> iterator = responseMsg.keys(); iterator
						.hasNext();) {
					String key = (String) iterator.next();
					msg += responseMsg.getString(key) + "\n";

				}
				Log.e(TAG, "msg " + msg);
			} catch (JSONException e) {
				e.printStackTrace();

			}
			// remove connection from shared pref
			ConnectionUtils.setDisconnecting(mContext, false, assignedFilter,
					msg);
			// update UI if active
			createSpotUIupdate.putExtra(RESUlT, false);
			Log.d(TAG, "CreateSpotFailed" + msg);
		}

		}
		
		Log.e(TAG,"reposnse done");
		sendBroadcast(createSpotUIupdate);
		Log.e(TAG,"send broad cast");
	}

	@Override
	protected void onNoResponse(String msg) {
		// remove connection from shared pref keeping result and reason
		ConnectionUtils.setDisconnecting(mContext, false, assignedFilter, msg);
		// update UI if active
		Intent newSpotUIupdate = new Intent(assignedFilter);
		newSpotUIupdate.putExtra(RESUlT, false);
		sendOrderedBroadcast(newSpotUIupdate, null);

	}

	@Override
	protected HttpRequestBase initRequest() {
		try {
			isEdit = extras.getBoolean(SpotCreateEditActivity.IS_EDIT, false);
			extras.remove(SpotCreateEditActivity.IS_EDIT);
			if (!isEdit) {
				HttpPost req = new HttpPost(API_URL + REQUEST_URL);
				req.setEntity(createPostBody());
				return req;
			} else {
				HttpPut req = new HttpPut(API_URL + REQUEST_URL + "/"
						+ extras.getLong(Spot.SPOT_ID));
				extras.remove(Spot.SPOT_ID);
				req.setEntity(createPostBody());
				return req;
			}

		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;

	}

	private HttpEntity createPostBody() throws UnsupportedEncodingException {
		JSONObject spot = new JSONObject();
		// to create image object
		JSONObject image = new JSONObject();
		// Creating Body
		JSONObject bodyData = new JSONObject();

		// extracting image info
		try {
			if (extras.containsKey(Spot.SPOT_FILE)) {
				image.put(Spot.SPOT_FILE, extras.getString(Spot.SPOT_FILE));
				extras.remove(Spot.SPOT_FILE);

				if (extras.containsKey(Spot.SPOT_FILENAME)) {
					image.put(Spot.SPOT_FILENAME,
							extras.getString(Spot.SPOT_FILENAME));
					extras.remove(Spot.SPOT_FILENAME);
				}
				// add image to body
				bodyData.put(IMAGE, image);
			}

			if (extras != null) {

				Set<String> extrasKeys = extras.keySet();
				if (!extrasKeys.isEmpty()) {

					for (String key : extrasKeys)
						try {
							bodyData.put(key, extras.get(key).toString());
						} catch (JSONException e) {
							e.printStackTrace();
						}
				}
			}

			// add outer spot
			spot.put(SPOT, bodyData);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		Log.e(TAG, spot.toString());
		return new ByteArrayEntity(spot.toString().getBytes("UTF-8"));
	}

}
